import React, { useState, useEffect } from 'react';
import { useGameStore } from '../store/gameStore';
import { MoodType, MoodSystem } from '../systems/MoodSystem';
import { Sparkles, Trophy, Star } from 'lucide-react';

interface MoodPanelProps {
  className?: string;
}

const MoodPanel: React.FC<MoodPanelProps> = ({ className = '' }) => {
  const { gameState, getMoodStatistics, forceSpawnMoodItem } = useGameStore();
  const [statistics, setStatistics] = useState<any>(null);
  const [showDetails, setShowDetails] = useState(false);

  // 更新统计信息
  useEffect(() => {
    const updateStats = () => {
      const stats = getMoodStatistics();
      setStatistics(stats);
    };

    updateStats();
    const interval = setInterval(updateStats, 1000); // 每秒更新一次

    return () => clearInterval(interval);
  }, [getMoodStatistics]);

  // 意境类型配置
  const moodConfigs = MoodSystem.getAllMoodConfigs();

  // 稀有度颜色配置
  const rarityColors = {
    common: 'text-gray-600 bg-gray-100',
    rare: 'text-purple-600 bg-purple-100',
    epic: 'text-yellow-600 bg-yellow-100'
  };

  // 稀有度名称
  const rarityNames = {
    common: '常见',
    rare: '稀有',
    epic: '史诗'
  };

  if (!statistics) {
    return (
      <div className={`bg-white rounded-lg shadow-md p-4 ${className}`}>
        <div className="text-gray-500 text-center">意境系统加载中...</div>
      </div>
    );
  }

  return (
    <div className={`bg-white rounded-lg shadow-md p-4 ${className}`}>
      {/* 面板标题 */}
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center space-x-2">
          <Sparkles className="w-5 h-5 text-purple-600" />
          <h3 className="text-lg font-semibold text-gray-800">意境收集</h3>
        </div>
        <button
          onClick={() => setShowDetails(!showDetails)}
          className="text-sm text-purple-600 hover:text-purple-800 underline"
        >
          {showDetails ? '收起' : '详情'}
        </button>
      </div>

      {/* 总体统计 */}
      <div className="grid grid-cols-2 gap-4 mb-4">
        <div className="bg-gradient-to-r from-purple-50 to-pink-50 rounded-lg p-3">
          <div className="flex items-center space-x-2">
            <Trophy className="w-4 h-4 text-purple-600" />
            <span className="text-sm text-gray-600">已收集</span>
          </div>
          <div className="text-xl font-bold text-purple-700">
            {statistics.totalCollected}
          </div>
        </div>
        
        <div className="bg-gradient-to-r from-blue-50 to-cyan-50 rounded-lg p-3">
          <div className="flex items-center space-x-2">
            <Star className="w-4 h-4 text-blue-600" />
            <span className="text-sm text-gray-600">意境值</span>
          </div>
          <div className="text-xl font-bold text-blue-700">
            {gameState.moodValue}
          </div>
        </div>
      </div>

      {/* 当前场上的意境物品 */}
      <div className="mb-4">
        <h4 className="text-sm font-semibold text-gray-700 mb-2">场上意境</h4>
        <div className="flex flex-wrap gap-2">
          {gameState.moodItems.filter(item => !item.collected).map(item => {
            const config = moodConfigs[item.type];
            const elapsed = Date.now() - item.createdTime;
            const remainingTime = Math.max(0, item.lifespan - elapsed);
            const timePercent = (remainingTime / item.lifespan) * 100;
            
            return (
              <div
                key={item.id}
                className={`relative px-2 py-1 rounded text-xs ${rarityColors[item.rarity]} border`}
              >
                <div className="flex items-center space-x-1">
                  <span>{config.symbol}</span>
                  <span>{config.name}</span>
                  <span className="text-xs">+{item.value}</span>
                </div>
                
                {/* 剩余时间进度条 */}
                <div className="absolute bottom-0 left-0 right-0 h-0.5 bg-gray-200 rounded-b">
                  <div 
                    className={`h-full transition-all duration-1000 rounded-b ${
                      timePercent > 50 ? 'bg-green-400' : 
                      timePercent > 25 ? 'bg-yellow-400' : 'bg-red-400'
                    }`}
                    style={{ width: `${timePercent}%` }}
                  />
                </div>
              </div>
            );
          })}
          
          {gameState.moodItems.filter(item => !item.collected).length === 0 && (
            <div className="text-sm text-gray-500 italic">暂无意境物品</div>
          )}
        </div>
      </div>

      {/* 详细统计 */}
      {showDetails && (
        <div className="space-y-4">
          {/* 按类型统计 */}
          <div>
            <h4 className="text-sm font-semibold text-gray-700 mb-2">类型统计</h4>
            <div className="grid grid-cols-2 gap-2">
              {Object.entries(statistics.typeStats).map(([type, stats]: [string, any]) => {
                const config = moodConfigs[type as MoodType];
                return (
                  <div key={type} className="flex items-center justify-between p-2 bg-gray-50 rounded">
                    <div className="flex items-center space-x-2">
                      <span className="text-sm">{config.symbol}</span>
                      <span className="text-sm text-gray-700">{config.name}</span>
                    </div>
                    <div className="text-xs text-gray-600">
                      {stats.count}个 (+{stats.value})
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          {/* 按稀有度统计 */}
          <div>
            <h4 className="text-sm font-semibold text-gray-700 mb-2">稀有度统计</h4>
            <div className="space-y-2">
              {Object.entries(statistics.rarityStats).map(([rarity, stats]: [string, any]) => (
                <div key={rarity} className="flex items-center justify-between p-2 bg-gray-50 rounded">
                  <div className="flex items-center space-x-2">
                    <div className={`w-3 h-3 rounded-full ${
                      rarity === 'epic' ? 'bg-yellow-400' :
                      rarity === 'rare' ? 'bg-purple-400' : 'bg-gray-400'
                    }`} />
                    <span className="text-sm text-gray-700">{rarityNames[rarity as keyof typeof rarityNames]}</span>
                  </div>
                  <div className="text-xs text-gray-600">
                    {stats.count}个 (+{stats.value})
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}

      {/* 开发模式：强制生成按钮 */}
      {process.env.NODE_ENV === 'development' && (
        <div className="mt-4 pt-4 border-t border-gray-200">
          <div className="text-xs text-gray-500 mb-2">开发模式</div>
          <div className="grid grid-cols-3 gap-2">
            <button
              onClick={() => forceSpawnMoodItem('moon')}
              className="px-2 py-1 text-xs bg-gray-100 text-gray-600 rounded hover:bg-gray-200"
            >
              🌙 明月
            </button>
            <button
              onClick={() => forceSpawnMoodItem('wind')}
              className="px-2 py-1 text-xs bg-green-100 text-green-600 rounded hover:bg-green-200"
            >
              🌬️ 松风
            </button>
            <button
              onClick={() => forceSpawnMoodItem('bamboo')}
              className="px-2 py-1 text-xs bg-green-100 text-green-600 rounded hover:bg-green-200"
            >
              🎋 竹影
            </button>
            <button
              onClick={() => forceSpawnMoodItem('lotus')}
              className="px-2 py-1 text-xs bg-pink-100 text-pink-600 rounded hover:bg-pink-200"
            >
              🪷 荷香
            </button>
            <button
              onClick={() => forceSpawnMoodItem('crane')}
              className="px-2 py-1 text-xs bg-yellow-100 text-yellow-600 rounded hover:bg-yellow-200"
            >
              🕊️ 仙鹤
            </button>
            <button
              onClick={() => forceSpawnMoodItem('mountain')}
              className="px-2 py-1 text-xs bg-blue-100 text-blue-600 rounded hover:bg-blue-200"
            >
              ⛰️ 远山
            </button>
          </div>
        </div>
      )}
    </div>
  );
};

export default MoodPanel;